module CCD_Capture(
	//CCD side
	iVSYNC,						//Vertical sync output from CCD, indicates new frame			
	iHREF,						//Horizontal window reference output, HIGH during a line (active window)
	iPCLK,						//Pixel clock. Data is stable at rising edge.
	iFODD,						//Odd line signal, effective in interlaced mode only
	iDATA_UV_RB,				//Digital data output (UV or RB channel)
	iDATA_Y_G,					//Digital data output (Y or G channel)
	//Output signals
	oRST,							//CCD chip reset
	oPWND,						//Power down mode
	//RAM side
	oWR_DATA,
	oWR_ADDR,
	oWR_CLK,
	//Image Processor Side
	X_Count,
	Y_Count,
	//UART mode
	iCAPTURE_EN,
	oCAPTURE_STOPPED,
	oIDLE
);

parameter WIDTH = 640;
parameter HEIGHT = 480;

//Incoming data lines
input [7:0] iDATA_UV_RB;					
input [7:0] iDATA_Y_G;

input iCAPTURE_EN;
output oCAPTURE_STOPPED;
assign oCAPTURE_STOPPED = ~FrameEnabled;
output oIDLE;
//assign oIDLE = ~iHREF;
assign oIDLE = idle;

//Incomming sync signals
input iVSYNC, iHREF, iPCLK, iFODD;

//Other user signals
output oRST;
assign oRST = 1'b0;
output oPWND;
assign oPWND = 1'b0;

//RAM side
output [7:0] oWR_DATA;
assign oWR_DATA = (FrameEnabled & lStart) ? iDATA_Y_G : 8'd0;
output [18:0] oWR_ADDR;
assign oWR_ADDR = (Y_Count*WIDTH + X_Count);
output oWR_CLK;
assign oWR_CLK = (FrameEnabled & lStart) ? iPCLK : 1'b0;

//Misc register for counting pixels and frames
output reg [9:0] X_Count;	//480
output reg [9:0] Y_Count;	//640

reg lStart;  // <= HREF
reg FrameEnd;  
reg FrameEnabled;  // <=iCAPTURE_EN
reg idle;
reg prev_VSYNC;
always@(posedge iPCLK)
begin
	prev_VSYNC <= iVSYNC;
	
	//Check frame start
	if({prev_VSYNC,iVSYNC}==2'b01) begin
		X_Count <= 10'd0;
		Y_Count <= 10'd0;
		idle <= 1'b0;
	end
			
	//Pixel counting
	if(lStart) begin
		if(X_Count < (WIDTH-1)) begin
			X_Count <= X_Count + 1'b1;					
		end
		else begin
			X_Count <= 10'd0;
			Y_Count <= Y_Count + 1'b1;
		end
	end
	
	if(oWR_ADDR == (HEIGHT*WIDTH-1)) begin
		FrameEnabled <= iCAPTURE_EN;
		idle <= 1'b1;
	end
end


//finding HREF
always@(negedge iPCLK)
begin
	//Check active line
	lStart <= iHREF;
end

endmodule
